package com.onstar.cn.tab.weight;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TabHost;

import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.tab.util.TabUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * tabHost 处理在Activity中添加tab以及一些tab的其他事件共有处理
 * 
 * @author 7828wc
 *
 */
public class CustomTabHost extends TabHost {
	private List<String> tabTags = new ArrayList<String>();
	private OnTabChangedListener onTabChangedListener;
	private View lastView;
	public CustomTabHost(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public CustomTabHost(Context context) {
		super(context);
	}

	/**
	 * Add tab to layout
	 */
	public void addTab(Class<? extends Activity> cls) {
		if (!CommonUtil.isNull(cls)) {
			Intent intent = new Intent(getContext(), cls);
			String tabTag = TabUtils.getTagName(cls);
			tabTags.add(tabTag);
			TabSpec tabSpec = this.newTabSpec(tabTag);
			tabSpec.setIndicator(tabTag).setContent(intent);
			super.addTab(tabSpec);
		}
	}

	/**
	 * 设置Current tab
	 * 
	 * @param cls
	 */
	public void setCurrentTabByTag(Class<? extends Activity> cls) {
		if(lastView != null) {
			lastView.setVisibility(View.GONE);
		}
		FrameLayout frameLayout = getTabContentView();
		frameLayout.setVisibility(View.VISIBLE);
		lastView = frameLayout;
		String tabTag = TabUtils.getTagName(cls);
		// super.setCurrentTabByTag(tabTag);
		LogManager.getInstance().d( "getCurrentTab:" + getCurrentTab());

		 for (int i = 0; i < tabTags.size(); i++) {
		 if (tabTag.equals(tabTags.get(i))) {
		 super.setCurrentTab(i);
		 break;
		 }
		 }
		if (onTabChangedListener != null) {
			onTabChangedListener.onTabChanged(tabTag);
		}
	}

	@Override
	public void setCurrentTabByTag(String tag) {
		// super.setCurrentTabByTag(tag);
		for (int i = 0; i < tabTags.size(); i++) {
			if (tag.equals(tabTags.get(i))) {
				super.setCurrentTab(i);
				break;
			}
		}
//		View mCurrentView = spec.mContentStrategy.getContentView();
//		getTabContentView().addView(mCurrentView,
//				new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
		if (onTabChangedListener != null) {
			onTabChangedListener.onTabChanged(tag);
		}
	}

	public void setOnTabChangedListener(OnTabChangedListener onTabChangedListener) {
		this.onTabChangedListener = onTabChangedListener;
	}

	public List<String> getTabTags() {
		return tabTags;
	}

	public interface OnTabChangedListener {
		void onTabChanged(String tagId);
	}

}
